package com.ray.service;

import com.alibaba.fastjson.JSONObject;
import com.google.appengine.api.search.query.ExpressionParser.negation_return;
import com.google.appengine.api.search.query.QueryParser.andOp_return;
import com.ray.bean.CompanyBean;
import com.ray.bean.DatatablesViewPageBean;
import com.ray.bean.DepartmentBean;
import com.ray.bean.PersonBean;
import com.ray.bean.RecruitApplyBean;
import com.ray.bean.UserBean;
import com.ray.bean.WeiXinPeopleBean;
import com.ray.bean.WorkExperienceBean;
import com.ray.exception.ServiceException;
import com.ray.mapper.CompanyMapper;
import com.ray.mapper.UserMapper;
import com.ray.pojo.MyUser;
import com.ray.pojo.UserDeptWorkPojo;
import com.ray.util.MailUtil;
import com.ray.util.ReturnStringUtil;
import com.ray.util.StringUtil;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

import net.sf.json.JSONArray;

import org.apache.ibatis.javassist.ClassMap;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.xb.xsdschema.impl.PublicImpl;
import org.junit.validator.PublicClassValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.TextMessage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.RejectedExecutionException;
import java.util.stream.Collectors;


@Service
public class UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    ApprovalService approvalService;
    @Autowired
    BasicDataService basicDataService;
    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    WeiXinPeopleService weiXinPeopleService;
    @Autowired
    WeiXinService weiXinService;
    @Autowired
    WorkshopService workshopService;

    public MyUser getUser(MyUser user) throws ServiceException {
        MyUser myUser = userMapper.getUser(user);
        if (null == myUser) {
            throw new ServiceException("用户名或密码不正确");
        }
        /**
         * 查询公司,通过用户数据中的公司名称 by 李斌 at 2018-04-20
         */
        CompanyBean company = userMapper.getCompanyInfo(user.getCompany());
        if (company == null) {
            company = new CompanyBean();
        }
        	/*增加软件到期服务时间判断*/
        if(company.getEndTime() != null) {
        	 DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
	    	try {
				if(df.parse(company.getEndTime()).getTime() < new Date().getTime()) {
					 throw new ServiceException("抱歉,系统服务已到期,请续费");
				}
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
        myUser.setCompanyInfo(company);
        myUser.setPassword("");
        /**取消  在查用户的时候添加了公司id  nate
         * 添加公司表公司id ssg
         */
//        myUser.setCompanyId(basicDataService.getCompanyId(myUser.getCompany()));
        return myUser;
    }
    
    /**
     * 获取公司信息
     * @param companyName
     * @return
     */
    public CompanyBean getCompanyInfo(String companyName) {
    	return  userMapper.getCompanyInfo(companyName);
    }


    /**
     * 通过用户id获取用户
     *
     * @param myUser
     * @return
     */
    public MyUser getUserByUserId(MyUser myUser) {
        return userMapper.getUser(myUser);
    }

    public UserBean getManager(String workShop) {
        String wei = "未设置";
        UserBean userBean = userMapper.getManager(workShop);
        if (null == userBean) {
            userBean = new UserBean();
            userBean.setUserName(wei);
            userBean.setPhone(wei);
            userBean.setShortPhone(wei);
            userBean.setWorkShop(wei);
            userBean.setAvatar("img/xx.png");
        }
        if (userBean.getAvatar().equals("")) {
            userBean.setAvatar("img/xx.png");
        }
        return userBean;
    }


    //通过微信用户id获取用户信息
    public UserBean getUserByWeiXinId(String weiXinUserId) {
        UserBean userBean = userMapper.getUserByWeiXinId(weiXinUserId);
        return userBean;
    }

    public void insertUser(UserBean userBean) {
        userMapper.insertUser(userBean);
    }

    public boolean jiaoYanPass(MyUser user) {
        MyUser myUser = userMapper.getUser(user);
        if (null == myUser) {
            return false;
        }
        return true;
    }


    //	修改密码
    public void updatePassword(MyUser myuser) {
        userMapper.updatePassword(myuser);
    }


    public String getDepartment(String userName) {
        return userMapper.getDepartment(userName);
    }


    //通过表格上传文件
    public List<UserBean> addPeopleByFile(MultipartFile filename, MyUser myUser) throws ServiceException, IOException {
        List<UserBean> returnList = new ArrayList<UserBean>();
        Set<String> nameSet = new HashSet<String>();
        Set<String> phoneSet = new HashSet<String>();
        String excelName = filename.getOriginalFilename();
        boolean suffixName = excelName.endsWith(".xlsx");
        if (!suffixName) {
            throw new ServiceException("请按照模板上传xlsx格式文件");
        }
        List<UserBean> userList = new ArrayList<UserBean>();
        XSSFWorkbook xwb;
        xwb = new XSSFWorkbook(filename.getInputStream());
        XSSFSheet sheet = xwb.getSheetAt(0);
        int rowNum = sheet.getLastRowNum();//得到有效的行数
        int colNum = sheet.getRow(0).getLastCellNum();
        UserBean user;
        for (int rowIndex = 1; rowIndex < rowNum + 1; rowIndex++) {
            user = new UserBean();
            XSSFRow row = sheet.getRow(rowIndex);
            for (int cellIndex = 0; cellIndex < colNum; cellIndex++) {
                XSSFCell cell = row.getCell(cellIndex);
                try {
                    switch (cellIndex) {
                        case 0:
                            user.setUserName(cell.getStringCellValue().trim());
                            break;
                        case 1:
                            user.setPhone(cell.getStringCellValue().trim());
                            break;
                        case 2:
                            user.setEmail(cell.getStringCellValue().trim());
                            break;
                    }
                } catch (Exception e) {
                    throw new ServiceException("请按照模板格式填写数据");
                }
            }
            user.setCompany(myUser.getCompany());
            user.setPassword("123");
            user.setStatus("开启");
            nameSet.add(user.getUserName());
            phoneSet.add(user.getPhone());
//			UserBean us=userMapper.getUserBean(user);
            if (this.checkUser(user.getUserName(), user.getPhone(), null, user.getCompany())) {
                userList.add(user);
            } else {
                returnList.add(user);
            }
        }
        xwb.close();
        if (nameSet.size() < (userList.size() + returnList.size()) || phoneSet.size() < (userList.size() + returnList.size())) {
            throw new ServiceException("表格中用户名或手机号重复");
        }
        userMapper.addPeopleByFile(userList);
        return returnList;
    }

    //校验用户名  （校验通过）无返回true   （校验不通过）有返回false
    //此方法调用两次  一次传一种参数
    public boolean checkUser(String userName, String phone, String userId, String company) {
        Assert.isTrue(userName != null || phone != null, "用户名和手机号必填一项");
        boolean bool = false;
        List<String> userIdList = userMapper.checkUser(userName, phone, userId, company);
        if (userIdList == null || userIdList.size() <= 0) {
            bool = true;
        }
        return bool;
    }

    //获取车间下人员
    public List<UserBean> getDeptUser(Map map) throws ServiceException {
        List<UserBean> userList = userMapper.getDeptUser(map);
        String workshopName = map.get("workshopName").toString();
//		if(null==userList || userList.size()<=0) {
//			WorkshopProductionCycleBean wc=basicDataService.getWCById(workshopName);
////			throw new ServiceException(wc.getWorkshopName()+"车间还没有成员");
//		}
        return userList;
    }


    //    通过用户名或手机号获取用户信息
    public List<UserBean> querryUserByNameOrPhone(String nameOrPhone, String company) {
        return userMapper.querryUserByNameOrPhone(nameOrPhone, company);
    }

    //查找公司所有人
    public List<UserBean> queryAllUser(Map map) {
        return userMapper.queryAllUser(map);
    }

    //通过任意条件获取用户
    public UserBean getUserBean(UserBean userBean) {
        return userMapper.getUserBean(userBean);
    }

    //通过用户名和公司获取用户信息
    public UserBean getUserByName(Map map) throws ServiceException {
        UserBean userBean = new UserBean();
        userBean.setCompany(map.get("loginCompany").toString());
        userBean.setUserName(map.get("name").toString());
        userBean = userMapper.getUserBean(userBean);
        if (null == userBean) {
            throw new ServiceException("该用户不存在");
        }
        return userBean;
    }


    //获取id对应的所有用户
//    public List<UserBean> getHaveUser(List<String> haveIdList) {
//        return userMapper.getHaveUser(haveIdList);
//    }


    //	获取不在id中的所有用户
//    public List<UserBean> getNoHaveUser(Map map) {
//        return userMapper.getNoHaveUser(map);
//    }


    //获取部门用户
    public List<UserBean> getDepartmentUser(Map map) {
        return userMapper.getDepartmentUser(map);
    }

    /**
     * 获取公司的所有部门
     *
     * @return List<DepartmentBean>
     * @throws
     * @date 2018年5月11日 下午7:12:12
     * @author 李斌
     */
    public List<DepartmentBean> getAllDepartment(Map<String, Object> map) {
        return userMapper.getAllDepartment(map);
    }

    /**
     * 通过部门名称获取用户
     *
     * @return List<String>
     * @throws
     * @date 2018年6月1日 上午11:44:17
     * @author 李斌
     */
    public List<String> getUserIdByDeptName(Map map) {
        // TODO Auto-generated method stub
        return userMapper.getUserIdByDeptName(map);
    }

    /**
     * 通过部门名称获取用户
     *
     * @return List<String>
     * @throws
     * @date 2018年6月1日 上午11:44:17
     * @author 李斌
     */
    public List<UserBean> getDeptUserByDeptName(Map map) {
        List<UserBean> userList = userMapper.getDeptUserByDeptName(map);
        //查询公司表
        int isAutoApproval = companyMapper.getIsAutoApprovalByCompany(map);
        //如果isAutoApproval为1说明验收人可以为登录人
        if (isAutoApproval == 1) {
            UserBean userBean = new UserBean();
            userBean.setId(map.get("loginUserId").toString());
            userBean.setUserName(map.get("loginUserName").toString());
            boolean flag = false;
            for (UserBean user : userList) {
                if (userBean.getId().equals(user.getId())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                userList.add(userBean);
            }
        }
        return userList;
    }


    /**
     * 通过登录令牌查找用户
     *
     * @param loginToken
     * @return
     * @throws IOException 
     */
    public MyUser getUserByToken(Map map,String redirUrl) throws IOException {
    	List<MyUser> list=userMapper.getUserByToken(map);
    	if(null==list || list.size()<=0) {
    		return null;
    	}
    	if(list.size()==1) {
    		return list.get(0);
    	}
    	if(list.size()>1) {
//    		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();  
//            HttpServletRequest request = attributes.getRequest();  
//            MyUser user=(MyUser)request.getSession().getAttribute("userLogin");
    		JSONArray jsonArray=new JSONArray();
    		for(MyUser mm:list) {
    			net.sf.json.JSONObject jsonObject=new net.sf.json.JSONObject();
    			jsonObject.put("openid", mm.getOpenid());
    			jsonObject.put("company", mm.getCompany());
    			jsonArray.add(jsonObject);
    		}
    		String string=jsonArray.toString();
    		string=URLEncoder.encode(string,"UTF-8");
    		string="/phoneApp/companySelect?userStr="+string+"&url="+redirUrl;
    		Assert.isTrue(false,"重定向错误"+string);
    	}
        return list.get(0);
    }

    /**
     * 通过用户ids 获取用户信息
     * @return List<UserBean>
     * @throws
     * @date 2018年6月2日 下午2:32:15
     * @author 李斌
     */
    public List<UserBean> getUserByIds(Map<String, Object> approvalParam) {
        return userMapper.getUserByIds(approvalParam);
    }

    /**
     * 获取单个用户信息
     *
     * @return UserBean
     * @throws
     * @date 2018年6月5日 下午2:04:21
     * @author 李斌
     */
    public UserBean getUserById(Map map) {
        return userMapper.getUserById(map);
    }


    /**
     * 获取接受生产异常消息的人  车间主管以上以及公司注册人
     * @param company(公司)
     * @param workShopId(车间id)
     * @return
     */
//	public List<WeiXinPeopleBean> getAcceptProductionExceptionUser(String company, String workShopId,String deptId) {
//		return userMapper.getAcceptProductionExceptionUser(company,workShopId,deptId);
//	}


    /**
     * 发送微信验证消息
     *
     * @param userId
     * @return
     */
    public int sendVerificationCode(String userId, HttpServletRequest request) {
        int returnType = 0;
        List<String> openIdList = weiXinPeopleService.getOpenIdByUserId(userId);
        if (openIdList == null || openIdList.size() <= 0) {
            returnType = 1;//账号未关联微信
        } else {
            boolean bool = false;
            String accessToken = weiXinService.getAccessToken(request);
            Random rad = new Random();
            String xx = rad.nextInt(1000000) + "";//验证码
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String dateStr = sdf.format(new Date());
            for (String str : openIdList) {
                JSONObject data = WeixinTemplateList.packJsonToValidCode("眼镜erp登陆验证码", xx, dateStr, "特别提醒：此验证码三分钟内有效", null, null, null, null);
                String result = WeixinTemplateSender.sendWechatmsgToUser(str, WeiXinParamesUtil.verificationCodeTemplateID, null, data, accessToken);
                if ("success".equals(result) && !bool) {//发送成功一次就可以
                    bool = true;
                }
            }
            if (!bool) {
                returnType = 2;//发送不成功
            } else {
                workshopService.insertLoginToken(xx, userId);
            }
        }
        return returnType;
    }

//	public void insertAccessToken(String accessToken) {
//		userMapper.insertAccessToken(accessToken,"轩昊科技");
//	};

    /**
     * 校验微信验证码
     *
     * @param user
     * @return
     */
    public boolean VerificationCode(MyUser user) {
        boolean bool = false;
        List<String> strList = userMapper.getVerificationCode(user);
        if (strList != null && strList.size() > 0) {
            bool = true;
        }
        return bool;
    }


    /**
     * 关联微信
     *
     * @param myUser
     */
    public void relationWeiXin(MyUser myUser) {
        Assert.notNull(myUser.getWeiXinPublicOpenId(), "未获取到微信号");
        List<String> openIdList = weiXinPeopleService.getOpenIdByUserId(myUser.getUserId());
        Assert.isTrue(openIdList == null || openIdList.size() <= 0, "此账号已经关联过其他微信");
        List<WeiXinPeopleBean> userIdList = weiXinPeopleService.getWeiXinPeopleByOpenId(myUser.getWeiXinPublicOpenId());
        List<WeiXinPeopleBean> checkRepaitList=userIdList.stream().filter(weixin->myUser.getCompany().equals(weixin.getCompany()) && !weixin.getUserId().equals(myUser.getUserId())).collect(Collectors.toList());
        Assert.isTrue(checkRepaitList.size()<=0,"此微信已关联过本公司其他账号");
//        Assert.isTrue(userIdList.get(0).getUserId() == null || "".equals(userIdList.get(0).getUserId()), "此微信已关联过其他账号");
//        List<WeiXinPeopleBean> weiXinPeopleList = weiXinPeopleService.getWeiXinPeopleByOpenId(myUser.getWeiXinPublicOpenId());
        WeiXinPeopleBean wxpb = new WeiXinPeopleBean();
        wxpb.setOpenid(myUser.getWeiXinPublicOpenId());
        wxpb.setUserId(myUser.getUserId());
        wxpb.setCompany(myUser.getCompany());
        wxpb.setUnionid(myUser.getUnionId());
        weiXinPeopleService.insertWeiXinPeople(wxpb);
        //第一次获取微信id
//        if (weiXinPeopleList == null || weiXinPeopleList.size() <= 0) {
        
//        } else {
//            weiXinPeopleService.updateWeiXinPeople(wxpb);
//        }
    }


    /**
     * 找回密码校验用户
     * @param companyName(公司名)
     * @param userName(用户名)
     * @param type(找回方式 1 为微信 2 为邮箱)
     * @return
     * @throws Exception
     */
    public UserBean checkUser(UserBean userBean, int type) {
        Assert.notNull(userBean, "未获取到参数");
        Assert.notNull(userBean.getCompany(), "未获取到公司名");
        Assert.notNull(userBean.getUserName(), "未获取到用户名");
        Assert.notNull(type, "未获取到类型");
        //获取用户
        UserBean user = userMapper.getUserBean(userBean);
        Assert.notNull(user, "该用户不存在");
        Random rad = new Random();
        String xx = rad.nextInt(1000000) + "";//验证码
        //找回方式为邮箱找回
        if (type == 2) {
            Assert.isTrue(user.getEmail() != null && !user.getEmail().equals(""), "该用户没有关联邮箱");
            String[] emailList = {user.getEmail()};
            try {
                MailUtil.sendMailHtml(emailList, null, "眼镜erp重设密码验证码", xx + "   特别提醒：此验证码三分钟内有效");
            } catch (Exception e) {
                e.printStackTrace();
                Assert.isTrue(1 == 2, "未知异常，邮箱验证码发送失败");
            }
        }
        //找回方式为微信找回
        if (type == 1) {
            List<String> openIdList = weiXinPeopleService.getOpenIdByUserId(user.getId());
            Assert.isTrue(openIdList != null && openIdList.size() > 0, "该账号未关联微信");
            boolean bool = false;
            String accessToken = weiXinService.getAccessToken(null);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            String dateStr = sdf.format(new Date());
            JSONObject data = WeixinTemplateList.packJsonToValidCode("眼镜erp重设密码验证码", xx, dateStr, "特别提醒：此验证码三分钟内有效", null, null, null, null);
            String result = WeixinTemplateSender.sendWechatmsgToUser(openIdList.get(0), WeiXinParamesUtil.verificationCodeTemplateID, null, data, accessToken);
            Assert.isTrue("success".equals(result), "验证码发送失败，请检查关联微信是否关注公众号");
        }
        workshopService.insertLoginToken(xx, user.getId());
        user.setId(null);
        return user;
    }


    /**
     * 找回密码校验用户
     *
     * @param companyName(公司名)
     * @param userName(用户名)
     * @param code(验证码)
     * @param password(新密码)
     * @return
     */
    public void updatePassworByCode(UserBean userBean, String code) {
        Assert.notNull(userBean, "未获取到参数");
        Assert.notNull(userBean.getCompany(), "未获取到公司名");
        Assert.notNull(userBean.getUserName(), "未获取到用户名");
        Assert.notNull(userBean.getPassword(), "未获取到密码");
        Assert.notNull(code, "未获取到验证码");
        //获取用户
        UserBean user = userMapper.getUserBean(userBean);
        Assert.notNull(user, "用户信息不正确");
        MyUser myUser = new MyUser();
        myUser.setUserId(user.getId());
        myUser.setVerificationCode(code);
        myUser.setPassword(userBean.getPassword());
        Assert.isTrue(this.VerificationCode(myUser), "验证码错误或已过期");
        userMapper.updatePassword(myUser);
    }

    /**
     * 获取人员信息,内含部门与车间信息
     * @return Object
     * @throws
     * @date 2018年9月5日 上午8:50:37
     * @author 李斌
     */
    public List<UserDeptWorkPojo> getUserByDeptAndWork(Map<String, Object> map) {
        List<UserDeptWorkPojo> userDeptWorkPojos = userMapper.getUserByDeptAndWork(map);
        return userDeptWorkPojos;
    }

    /**
     * 申请招聘
     * position 招聘职位
     * workShopId 车间id
     * count 招聘数量
     * @param map
     * @return
     */
	public String applyRecruit(Map<String, Object> map) {
		StringUtil.checkIsTrue(map, "position", "未获取到招聘职位");
		StringUtil.checkIsTrue(map, "workShopId", "未获取到招聘车间");
		StringUtil.checkIsTrue(map, "count", "未获取到招聘数量");
		StringUtil.checkIsTrue(map, "requirement", "未获取到岗位职责要求");
		StringUtil.checkIsTrue(map, "arrivalDate", "未获取到希望到岗日期");
	    int row = userMapper.addApplyRecruit(map);
	    Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.OPERATION_SUCCESS;
	}

	/**
	 * 获取招聘申请信息
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<RecruitApplyBean> getApplyRecruit(Map<String, Object> map) {
		DatatablesViewPageBean<RecruitApplyBean> datatablesViewPageBean = new DatatablesViewPageBean<RecruitApplyBean>();
		int count = userMapper.getApplyRecruitCount(map);
		List<RecruitApplyBean> list = this.getApplyRecruitList(map);
		datatablesViewPageBean.setReturnData(list);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		return datatablesViewPageBean;
	}

	@SuppressWarnings("unchecked")
	private List<RecruitApplyBean> getApplyRecruitList(Map map){
		return userMapper.getApplyRecruit(map);
	}
	
	public List<RecruitApplyBean> getApplyRecruitNoLogin(Map<String, Object> map) {
		StringUtil.checkIsTrue(map, "company", "未获取到公司");
		map.put("loginCompany", map.get("company"));
		return this.getApplyRecruitList(map);
	}
	
	
	/**
	 * 审核招聘申请
	 * @param map
	 * @return
	 */
	public String  approvalApplyRecruit(Map<String, Object> map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id");
		StringUtil.checkIsTrue(map, "status", "未获取到状态");
		int  status = Integer.parseInt(map.get("status").toString());
		map.remove("status");
        List<RecruitApplyBean> list = this.getApplyRecruitList(map);
		Assert.isTrue(list.size()>0,"该记录不存在");
		RecruitApplyBean recruitApplyBean = list.get(0);
		Assert.isTrue(recruitApplyBean.getStatus() == 0 ,"该记录已审核,不可再次操作");
		map.put("status", status);
		int row = userMapper.approvalApplyRecruit(map);
		Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.APPROVAL_SUCCESS;
	}

	
	/**
	 * 
	 * 应聘者扫码添加人员
	 * @param map 
	 * @return
	 * 部门  车间  职务   手机号  用户名 
	 */
	public String  addCandidateByQRCode(Map map) {
		String jsonStr = map.get("jsonStr").toString();
		net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(jsonStr);
		Map classMap = new HashMap();
		classMap.put("workExperienceList", WorkExperienceBean.class);
		PersonBean personBean = (PersonBean) net.sf.json.JSONObject.toBean(jsonObject, PersonBean.class, classMap);
		map.put("data", personBean);
		int  row = userMapper.addCandidateByQRCode(map);
		Assert.isTrue(row>0,"保存主信息失败");
		if(personBean.getWorkExperienceList() != null && personBean.getWorkExperienceList().size()>0) {
			int  detailRow = userMapper.addWorkExperience(map);
			Assert.isTrue(detailRow>0,"保存工作经历失败");
		}
		return ReturnStringUtil.ADD_SUCCESS;
	}

	/**
	 * 获取招聘记录
	 * @param map
	 * @return
	 */
	public DatatablesViewPageBean<PersonBean> getCandidateRecord(Map<String, Object> map) {
		DatatablesViewPageBean<PersonBean> datatablesViewPageBean = new DatatablesViewPageBean<PersonBean>();
		List<PersonBean> list = this.getCandidateRecordList(map);
		int  count = userMapper.getCandidateRecordListCount(map);
		datatablesViewPageBean.setReturnData(list);
		datatablesViewPageBean.setiTotalDisplayRecords(count);
		datatablesViewPageBean.setiTotalRecords(count);
		return datatablesViewPageBean;
	}

	
	/**
	 * 获取招聘记录
	 * @param map
	 * @return
	 */
	public List<PersonBean> getCandidateRecordList(Map map){
		return userMapper.getCandidateRecordList(map);
	}
	
	/**
	 * id 
	 * status 1入职  2不合格
	 * 审核招聘信息  （入职或不合格）
	 * @param map
	 * @return
	 */
	public String  approvalCandidate(Map<String, Object> map) {
		StringUtil.checkIsTrue(map, "id", "未获取到id");
		StringUtil.checkIsTrue(map, "status", "未获取到状态");
		int status = Integer.parseInt(map.get("status").toString());
		map.remove("status");
		List<PersonBean> list = this.getCandidateRecordList(map);
		Assert.isTrue(list.size()>0,"该记录不存在");
	    PersonBean personBean = list.get(0);
	    System.out.println(personBean.toString());
	    Assert.isTrue("0".equals(personBean.getStatus()),"该记录已审核");
		/**
		 * 如果是入职
		 */
		if(1==status) {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			personBean.setHiredate(simpleDateFormat.format(new Date()));
			basicDataService.insertPerson(personBean, map);
		}
		map.put("status", status);
	    int  row = userMapper.approvalCandidate(map);
	    Assert.isTrue(row>0,ReturnStringUtil.OPERATION_ERROR);
		return ReturnStringUtil.OPERATION_SUCCESS;
	}

	

}
